Expand description
§About Leptos
Leptos is a full-stack framework for building web applications in Rust. You can use it to build
- single-page apps (SPAs) rendered entirely in the browser, using client-side routing and loading or mutating data via async requests to the server
- multi-page apps (MPAs) rendered on the server, managing navigation, data, and mutations via
web-standard
<a>
and<form>
tags - progressively-enhanced single-page apps that are rendered on the server and then hydrated on the client,
enhancing your
<a>
and<form>
navigations and mutations seamlessly when WASM is available.
And you can do all three of these using the same Leptos code.
Take a look at the Leptos Book for a walkthrough of the framework. Join us on our Discord Channel to see what the community is building. Explore our Examples to see Leptos in action.
§Learning by Example
If you want to see what Leptos is capable of, check out the examples:
counter
is the classic counter example, showing the basics of client-side rendering and reactive DOM updatescounter_without_macros
adapts the counter example to use the builder pattern for the UI and avoids other macros, instead showing the code that Leptos generates.counters
introduces parent-child communication via contexts, and the<For/>
component for efficient keyed list updates.error_boundary
shows how to useResult
types to handle errors.parent_child
shows four different ways a parent component can communicate with a child, including passing a closure, context, and morefetch
introduces Resources, which allow you to integrate arbitraryasync
code like an HTTP request within your reactive code.router
shows how to use Leptos’s nested router to enable client-side navigation and route-specific, reactive data loading.slots
shows how to use slots on components.spread
shows how the spread syntax can be used to spread data and/or event handlers onto elements.counter_isomorphic
shows different methods of interaction with a stateful server, including server functions, server actions, forms, and server-sent events (SSE).todomvc
shows the basics of building an isomorphic web app. Both the server and the client import the same app code from thetodomvc
example. The server renders the app directly to an HTML string, and the client hydrates that HTML to make it interactive. You might also want to see how we usecreate_effect
to serialize JSON tolocalStorage
and reactively call DOM methods on references to elements.hackernews
andhackernews_axum
integrate calls to a real external REST API, routing, server-side rendering and hydration to create a fully-functional application that works as intended even before WASM has loaded and begun to run.todo_app_sqlite
andtodo_app_sqlite_axum
show how to build a full-stack app using server functions and database connections.tailwind
shows how to integrate TailwindCSS withtrunk
for CSR.
Details on how to run each example can be found in its README.
§Quick Links
Here are links to the most important sections of the docs:
- Reactivity: the
leptos_reactive
overview, and more details in- signals:
create_signal
,ReadSignal
, andWriteSignal
(andcreate_rw_signal
andRwSignal
) - computations:
create_memo
andMemo
async
interop:create_resource
andResource
for loading data usingasync
functions, andcreate_action
andAction
to mutate data or imperatively callasync
functions.- reactions:
create_effect
- signals:
- Templating/Views: the
view
macro - Routing: the
leptos_router
crate - Server Functions: the
server
macro,create_action
, andcreate_server_action
§Feature Flags
nightly
: Onnightly
Rust, enables the function-call syntax for signal getters and setters.csr
Client-side rendering: Generate DOM nodes in the browserssr
Server-side rendering: Generate an HTML string (typically on the server)hydrate
Hydration: use this to add interactivity to an SSRed Leptos appserde
(Default) In SSR/hydrate mode, usesserde
to serialize resources and send them from the server to the client.serde-lite
In SSR/hydrate mode, usesserde-lite
to serialize resources and send them from the server to the client.rkyv
In SSR/hydrate mode, usesrkyv
to serialize resources and send them from the server to the client.miniserde
In SSR/hydrate mode, usesminiserde
to serialize resources and send them from the server to the client.tracing
Adds additional support fortracing
to components.default-tls
Use default native TLS support. (Only applies when using server functions with a non-WASM client like a desktop app.)rustls
Userustls
. (Only applies when using server functions with a non-WASM client like a desktop app.)template_macro
Enables thetemplate!
macro, which offers faster DOM node creation for some use cases incsr
.
Important Note: You must enable one of csr
, hydrate
, or ssr
to tell Leptos
which mode your app is operating in. You should only enable one of these per build target,
i.e., you should not have both hydrate
and ssr
enabled for your server binary, only ssr
.
§A Simple Counter
use leptos::*;
#[component]
pub fn SimpleCounter( initial_value: i32) -> impl IntoView {
// create a reactive signal with the initial value
let (value, set_value) = create_signal( initial_value);
// create event handlers for our buttons
// note that `value` and `set_value` are `Copy`, so it's super easy to move them into closures
let clear = move |_| set_value.set(0);
let decrement = move |_| set_value.update(|value| *value -= 1);
let increment = move |_| set_value.update(|value| *value += 1);
view! {
<div>
<button on:click=clear>"Clear"</button>
<button on:click=decrement>"-1"</button>
<span>"Value: " {move || value.get().to_string()} "!"</span>
<button on:click=increment>"+1"</button>
</div>
}
}
Leptos is easy to use with Trunk (or with a simple wasm-bindgen setup):
#[component]
fn SimpleCounter(initial_value: i32) -> impl IntoView {
todo!()
}
pub fn main() {
mount_to_body(|| view! { <SimpleCounter initial_value=3 /> })
}
Re-exports§
pub use server_fn::ServerFn as _;
pub use leptos_config;
pub use leptos_dom;
pub use leptos_server;
pub use server_fn;
Modules§
- Callbacks define a standard way to store functions and closures. They are useful for component properties, because they can be used to define optional callback functions, which generic props don’t support.
- Types to make it easier to handle errors in your application.
- Types for all DOM events.
- Exports types for working with HTML elements.
- Utilities for simple isomorphic logging to the console or terminal.
- Exports types for working with MathML elements.
- Utilities for exporting nonces to be used for a Content Security Policy.
- This module contains the
Oco
(Owned Clones Once) smart pointer, which is used to store immutable references to values. This is useful for storing, for example, strings. - This prelude imports all signal types as well as all signal traits needed to use those types.
- Utilities for server-side rendering HTML.
- Types that handle asynchronous data loading via
<Suspense/>
. - Exports types for working with SVG elements.
Macros§
- Generates a
slice
into a struct with a default getter and setter. - The
view
macro uses RSX (like JSX, but Rust!) It follows most of the same rules as HTML, with the following differences: - Provides a simpler way to use
SignalUpdate::update
. - Provides a simpler way to use
StoredValue::update_value
. - The
view
macro uses RSX (like JSX, but Rust!) It follows most of the same rules as HTML, with the following differences: - Provides a simpler way to use
SignalWith::with
. - Provides a simpler way to use
StoredValue::with_value
.
Structs§
- An action synchronizes an imperative
async
call to the synchronous reactive system. - Additional
Attributes Deprecated A collection of additional HTML attributes to be applied to an element, each of which may or may not be reactive. - Iterator over additional HTML attributes.
- Props for the
AnimatedShow
component. - Props for the
Await
component. - Callbacks define a standard way to store functions and closures.
- Handle to dispose of a reactive node.
- A handle to an effect, can be used to explicitly dispose of the effect.
- Props for the
ErrorBoundary
component. - A struct to hold all the possible errors that could be provided by child Views
- Props for the
For
component. - Represents a group of
views
. - Represents its pending
<Suspense/>
fragment. - A single, global suspense context that will be checked when resources are read. This won’t be “blocked” by lower suspense components. This is useful for e.g., holding route transitions.
- Represents an HTML element.
- This struct serves as a convenient place to store details used for configuring Leptos. It’s used in our actix and axum integrations to generate the correct path for WASM, JS, and Websockets, as well as other configuration tasks. It shares keys with cargo-leptos, to allow for easy interoperability
- A wrapping type for an optional component prop, which can either be a signal or a non-reactive value, and which may or may not have a value. In other words, this is an
Option<MaybeSignal<Option<T>>>
that automatically flattens its getters. - An efficient derived reactive value based on other reactive values.
- An action that synchronizes multiple imperative
async
calls to the reactive system, tracking the progress of each one. - Contains a shared reference to a DOM node created while using the
view
macro to create your UI. - A reactive owner.
- Props for the
Portal
component. - Props for the
Provider
component. - The getter for a reactive signal.
- A signal that reflects the current state of an asynchronous task, allowing you to integrate
async
Future
s into the synchronous reactive system. - Unique ID assigned to a
Resource
. - Unique ID assigned to a Runtime.
- A signal that combines the getter and setter into one value, rather than separating them into a
ReadSignal
and aWriteSignal
. You may prefer this its style, or it may be easier to pass around in a context or as a function argument. - Allows running a future that has access to a given scope.
- A conditional signal that only notifies subscribers when a change in the source signal’s value changes whether the given function is true.
- Props for the
Show
component. - A wrapper for any kind of readable reactive signal: a
ReadSignal
,Memo
,RwSignal
, or derived signal closure. - A wrapper for any kind of settable reactive signal: a
WriteSignal
,RwSignal
, or closure that receives a value and sets a signal depending on it. - A non-reactive wrapper for any value, which can be created with
store_value
. - Props for the
Suspense
component. - A callback type that is
Send
andSync
if its input type isSend
andSync
. Otherwise, you can use exactly the way you useCallback
. - Props for the
Transition
component. - Reactive Trigger, notifies reactive code to rerun.
- New-type wrapper for the a function that returns a view with
From
andDefault
traits implemented to enable optional props in for example<Show>
and<Suspense>
. - The setter for a reactive signal.
Enums§
- Represents the different possible values an attribute node could have.
- Bind data through attributes, or behavior through event handlers, to an element. A value of any type able to provide an iterator of bindings (like a:
Vec<Binding>
), can be spread onto an element using the spread syntaxview! { <div {..bindings} /> }
. - Represents the different possible values a single class on an element could have, allowing you to do fine-grained updates to single items in
Element.classList
. - A statically typed event handler.
- Error returned from
Oco::try_from
for unsuccessful conversion fromOco<'_, [u8]>
toOco<'_, str>
. - A wrapper for a value that is either
T
orSignal<T>
. - “Owned Clones Once”: a smart pointer that can be either a reference, an owned value, or a reference-counted pointer. This is useful for storing immutable values, such as strings, in a way that is cheap to clone and pass around.
- Represents the different possible values an element property could have, allowing you to do fine-grained updates to single fields.
- Describes errors that can occur while serializing and deserializing data, typically during the process of streaming
Resource
s from the server to the client. - Type for errors that can occur when using server functions.
- Type for errors that can occur when using server functions.
- A leptos view which can be mounted to the DOM.
Traits§
- A wrapper trait for calling callbacks.
- Collects an iterator or collection into a
View
. - Converts some type into an
Attribute
. - Converts some type into a
Class
. - Converts some type into a
Property
. - Helper trait for converting
Fn() -> T
closures intoSignal<T>
. - Helper trait for converting
Fn(T)
intoSignalSetter<T>
. - Converts some type into a
Style
. - Converts the value into a
View
. - Describes an object that can be serialized to or from a supported format Currently those are JSON and Cbor
- This trait allows disposing a signal before its owner has been disposed.
- This trait allows getting an owned value of the signals inner type.
- Trait implemented for all signal types which you can
get
a value from, such asReadSignal
,Memo
, etc., which allows getting the inner value without subscribing to the current scope. - This trait allows setting the value of a signal.
- Trait implemented for all signal types which you can
set
the inner value, such asWriteSignal
andRwSignal
, which allows setting the inner value without causing effects which depend on the signal from being run. - This trait allows converting a signal into a async
Stream
. - This trait allows updating the inner value of a signal.
- This trait allows updating the signals value without causing dependant effects to run.
- This trait allows obtaining an immutable reference to the signal’s inner type.
- This trait allows getting a reference to the signals inner value without creating a dependency on the signal.
- This trait can be used when constructing a component that takes children without needing to know exactly what children type the component expects. This is used internally by the
view!
macro implementation, and can also be used explicitly when using the builder syntax.
Functions§
- A component that will show its children when the
when
condition istrue
. Additionally, you need to specify ahide_delay
. If thewhen
condition changes tofalse
, the unmounting of the children will be delayed by the specified Duration. If you provide the optionalshow_class
andhide_class
, you can create very easy mount / unmount animations. - Allows you to inline the data loading for an
async
block or server function directly into your view. This is the equivalent of combining acreate_resource
that only loads once (i.e., with a source signal|| ()
) with aSuspense
with nofallback
. - When you render a
Result<_, _>
in your view, in theErr
case it will render nothing, and search up through the view tree for an<ErrorBoundary/>
. This component lets you define a fallback that should be rendered in that error case, allowing you to handle errors within a section of the interface. - Iterates over children and displays them, keyed by the
key
function given. - Renders components somewhere else in the DOM.
- Uses the context API to
provide_context
to its children and descendants, without overwriting any contexts of the same type in its own reactive scope. - A component that will show its children when the
when
condition istrue
, and show the fallback when it isfalse
, without rerendering every time the condition changes. - If any
Resource
is read in thechildren
of this component, it will show thefallback
while they are loading. Once all are resolved, it will render thechildren
. - Wraps the given function so that, whenever it is called, it creates a child node owned by whichever reactive node was the owner when it was created, runs the function, and returns a disposer that can be used to dispose of the child later.
- Batches any reactive updates, preventing effects from running until the whole function has run. This allows you to prevent rerunning effects if multiple signal updates might cause the same effect to run.
- Creates an Action to synchronize an imperative
async
call to the synchronous reactive system. - Creates a “blocking”
Resource
. When server-side rendering is used, this resource will cause any<Suspense/>
you read it under to block the initial chunk of HTML from being sent to the client. This means that if you set things like HTTP headers or<head>
metadata in that<Suspense/>
, that header material will be included in the server’s original response. - Effects run a certain chunk of code whenever the signals they depend on change.
create_effect
queues the given function to run once, tracks its dependence on any signal values read within it, and reruns the function whenever the value of a dependency changes. - Creates an effect; unlike effects created by
create_effect
, isomorphic effects will run on the server as well as the client. - Creates an efficient derived reactive value based on other reactive values.
- Creates a MultiAction to synchronize an imperative
async
call to the synchronous reactive system. - Creates a shared reference to a DOM node created while using the
view
macro to create your UI. - Like
create_memo
,create_owning_memo
creates an efficient derived reactive value based on other reactive values, but with two differences: - Takes a memoized, read-only slice of a signal. This is equivalent to the read-only half of
create_slice
. - Creates an effect exactly like
create_effect
, but runs immediately rather than being queued until the end of the current microtask. This is mostly used inside the renderer but is available for use cases in which scheduling the effect for the next tick is not optimal. - Creates a new reactive runtime and sets it as the current runtime.
- Creates a reactive signal with the getter and setter unified in one value. You may prefer this style, or it may be easier to pass around in a context or as a function argument.
- Creates a conditional signal that only notifies subscribers when a change in the source signal’s value changes whether it is equal to the key value (as determined by
PartialEq
.) - Creates a conditional signal that only notifies subscribers when a change in the source signal’s value changes whether the given function is true.
- Creates an Action that can be used to call a server function.
- Creates a MultiAction that can be used to call a server function.
- Creates a signal, the basic reactive primitive.
- Creates a signal that always contains the most recent value emitted by a
Stream
. If the stream has not yet emitted a value since the signal was created, the signal’s value will beNone
. - Derives a reactive slice of an
RwSignal
. - Creates a
Trigger
, a kind of reactive primitive. - Creates a setter to access one slice of a signal. This is equivalent to the write-only half of
create_slice
. - The current reactive runtime.
- Returns the
Document
. - Helper function to extract
Event.target
from any event. - Helper function to extract
event.target.checked
from an event. - Helper function to extract
event.target.value
from an event. - Extracts a context value of type
T
from the reactive system by traversing it upwards, beginning from the current reactive owner and iterating through its parents, if any. The context value should have been provided elsewhere using provide_context. - Loads LeptosOptions from a Cargo.toml with layered overrides. If an env var is specified, like
LEPTOS_ENV
, it will override a setting in the file. It takes in an optional path to a Cargo.toml file. If None is provided, you’ll need to set the options as environment variables or rely on the defaults. This is the preferred approach for cargo-leptos. If Some(“./Cargo.toml”) is provided, Leptos will read in the settings itself. This option currently does not allow dashes in file or folder names, as all dashes become underscores - Runs the provided closure and mounts the result to the provided element.
- Runs the provided closure and mounts the result to the
<body>
. - Creates a cleanup function, which will be run when the current reactive owner is disposed.
- Provides a context value of type
T
to the current reactive node and all of its descendants. This can be consumed usinguse_context
. - The microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser’s event loop.
- Runs the given function between the next repaint using
Window.requestAnimationFrame
. - Runs the given function between the next repaint using
Window.requestAnimationFrame
, returning a cancelable handle. - Queues the given function during an idle period using
Window.requestIdleCallback
. - Queues the given function during an idle period using
Window.requestIdleCallback
, returning a cancelable handle. - Runs the given function as a child of the current Owner, once.
- Sets the current reactive runtime.
- Repeatedly calls the given function, with a delay of the given duration between calls, returning a cancelable handle. See
setInterval()
. - Repeatedly calls the given function, with a delay of the given duration between calls, returning a cancelable handle. See
setInterval()
. - Executes the given function after the given duration of time has passed.
setTimeout()
. - Executes the given function after the given duration of time has passed, returning a cancelable handle.
setTimeout()
. - Spawns and runs a thread-local
Future
in a platform-independent way. - Runs a future that has access to the provided
Owner
’s scope context. - Runs a future that has access to the provided
Owner
’s scope context. - Creates a non-reactive wrapper for any value by storing it within the reactive system.
- Attempts to batch any reactive updates, preventing effects from running until the whole function has run. This allows you to prevent rerunning effects if multiple signal updates might cause the same effect to run.
- Runs a future that has access to the provided
Owner
’s scope context. - Runs a future that has access to the provided
Owner
’s scope context. - Runs the given code with the given reactive owner.
- Suspends reactive tracking while running the given function.
- Extracts a context value of type
T
from the reactive system by traversing it upwards, beginning from the current reactive owner and iterating through its parents, if any. The context value should have been provided elsewhere usingprovide_context
. - A version of
create_effect
that listens to any dependency that is accessed insidedeps
and returns a stop handler. - Returns the
Window
. - Creates a window event listener from a typed event, returning a cancelable handle.
- Adds an event listener to the
Window
, typed as a genericEvent
, returning a cancelable handle. - Wraps the given function so that, whenever it is called, it is run in the reactive scope of whatever the reactive owner was when it was created.
- Runs the given code with the given reactive owner.
Type Aliases§
- A type for taking anything that implements
IntoAttribute
. - The most common type for the
children
property on components, which can only be called once. - A type for the
children
property on components that can be called more than once. - A type for the
children
property on components that can be called more than once, but may mutate the children.
Attribute Macros§
- Annotates a function so that it can be used with your template as a Leptos
<Component/>
. - Defines a component as an interactive island when you are using the
experimental-islands
feature of Leptos. Apart from the macro name, the API is the same as thecomponent
macro. - Declares that a function is a server function. This means that its body will only run on the server, i.e., when the
ssr
feature on this crate is enabled. - Annotates a struct so that it can be used with your Component as a
slot
.
Derive Macros§
- Derives a trait that parses a map of string keys and values into a typed data structure, e.g., for route params.